#include "stdafx.h"
#include "./zipfile.h"

ZipFile::ZipFile(string strZipPath)
: m_fZip(NULL)
{
	m_fZip = unzOpen(strZipPath.c_str());
}

ZipFile::~ZipFile()
{
	if (m_fZip)
	{
		unzClose(m_fZip);
		m_fZip = NULL;
	}
}

bool ZipFile::OpenFile(string strPath, IoOpen openflag)
{	
	if (!m_fZip)
	{
		return false;
	}

	int ret;
	ret = unzLocateFile(m_fZip, strPath.c_str(), 0);
	if (UNZ_OK != ret)
	{
		unzClose(m_fZip);
		return false;
	}

	ret = unzGetCurrentFileInfo(m_fZip, &m_fZipInfo, NULL, 0, NULL, NULL, NULL, NULL);

	if(UNZ_OK != ret)
	{
		unzClose(m_fZip);
		return false;
	}

	ret = unzOpenCurrentFile(m_fZip);
	if (UNZ_OK != ret)
	{
		return false;
	}

	return true;
}

void ZipFile::CloseFile()
{
	if (m_fZip)
	{
		unzCloseCurrentFile(m_fZip);
	}
}

size_t ZipFile::GetFileLength()
{
	if (!m_fZip)
	{
		return 0;
	}

	return m_fZipInfo.uncompressed_size;
}

size_t ZipFile::ReadFile(byte* buffer, size_t size)
{
	if (!m_fZip)
	{
		return 0;
	}

	if (!buffer)
	{
		return GetFileLength();
	}

	return unzReadCurrentFile(m_fZip, buffer, static_cast<unsigned int>(size));
}

size_t ZipFile::WriteFile(const byte* buffer, size_t size)
{
	//zip file readonly
	return 0;
}

long ZipFile::SeekFile(long offset, IOStub::IoSeek origin)
{
	if (!m_fZip)
	{
		return 0;
	}

	return unzseek(m_fZip, offset, origin);
}

long ZipFile::TellFile()
{
	if (!m_fZip)
	{
		return 0;
	}

	return unztell(m_fZip);
}